package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"text-fig-mgr/models"
	"text-fig-mgr/pkg"
)

func Register(c *gin.Context) {
	username := c.PostForm("username")
	password := pkg.Md5(c.PostForm("password"))
	data := models.User{
		Username: username,
		Password: password,
	}
	err := models.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "注册失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "注册成功",
		})
		return
	}

}

func Login(c *gin.Context) {
	username := c.Query("username")
	password := pkg.Md5(c.Query("password"))
	data := models.User{
		Username: username,
		Password: password,
	}
	err := models.DB.Debug().Find(&data).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "登录成功",
		})
		return
	}
}

func List(c *gin.Context) {
	title := c.Query("title")
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offest := (page - 1) * size
	var article []*models.Article
	err := models.DB.Debug().Where("title=?", title).Find(&article).Limit(size).Offset(offest).Error
	var total int64
	models.DB.Model(&models.Article{}).Count(&total)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":  200,
			"msg":   "成功",
			"data":  article,
			"count": total,
		})
		return
	}

}
